<template>
  <div class="sensitive-disease-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-row">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入疾病名称"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="searchForm.visibleScope"
          placeholder="可见范围"
          class="category-select"
          clearable
        >
          <el-option label="全部可见" value="1" />
          <el-option label="仅本人可见" value="2" />
        </el-select>

        <el-button @click="handleReset"> 重置 </el-button>
        <el-button type="primary" @click="handleSearch"> 搜索 </el-button>
      </div>
    </div>

    <!-- 提示信息 -->
    <div class="tip-section">
      <el-alert
        title="可添加敏感病名称，若报告中出现敏感词则根据设置的规则显示或不显示"
        type="info"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <div class="table-header">
        <h3>敏感疾病列表</h3>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        class="disease-table"
      >
        <el-table-column prop="name" label="疾病名称" />
        <el-table-column prop="visibleScope" label="可见权限" align="center">
          <template #default="{ row }">
            {{ row.visibleScope === "1" ? "全部可见" : "仅本人可见" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑敏感疾病' : '添加敏感疾病'"
      width="600px"
      :close-on-click-modal="false"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="疾病名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入疾病名称" />
        </el-form-item>
        <el-form-item label="可见权限" prop="visibleScope">
          <el-radio-group v-model="formData.visibleScope">
            <el-radio label="1">全部可见</el-radio>
            <el-radio label="2">仅本人可见</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="confirmLoading"
            @click="handleConfirm"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { sensitiveApi, type SensitiveDiseaseItem } from "@/api/sensitive";
import { Plus, Search } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref } from "vue";

interface SearchForm {
  name: string;
  visibleScope: string;
}

interface Pagination {
  currentPage: number;
  pageSize: number;
  total: number;
}

// 响应式数据
const searchForm = reactive<SearchForm>({
  name: "",
  visibleScope: ""
});

const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const tableData = ref<SensitiveDiseaseItem[]>([]);
const loading = ref(false);
const saveLoading = ref(false);
const dialogVisible = ref(false);
const confirmLoading = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();

const formData = reactive<SearchForm>({
  name: "",
  visibleScope: ""
});
const formRules: FormRules = {
  name: [{ required: true, message: "请输入疾病名称", trigger: "blur" }],
  visibleScope: [
    { required: true, message: "请选择可见权限", trigger: "change" }
  ]
};

// 加载数据的完整方法
const loadData = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      name: searchForm.name || undefined,
      visibleScope: searchForm.visibleScope || undefined
    };

    // 调用API
    const response = await sensitiveApi.searchSensitiveDisease(params);

    if (response.code === 0 && response.data) {
      const { list, total, pageNum, pageSize } = response.data;
      tableData.value = list;
      pagination.total = total;
      pagination.currentPage = pageNum;
      pagination.pageSize = pageSize;
    } else {
      ElMessage.error(response.message || "查询失败");
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败，请重试");
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.currentPage = 1;
  loadData();
};
const handleReset = () => {
  Object.assign(searchForm, {
    name: "",
    visibleScope: ""
  });
  loadData();
};
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadData();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadData();
};

const resetForm = () => {
  Object.assign(formData, {
    name: "",
    visibleScope: "" // 设置默认值为"全部可见"
  });
  formRef.value?.clearValidate();
};

const handleAdd = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};
const handleEdit = (row: SensitiveDiseaseItem) => {
  isEdit.value = true;
  Object.assign(formData, {
    name: row.name,
    visibleScope: row.visibleScope,
    tagId: row.tagId
  });
  dialogVisible.value = true;
};

const handleConfirm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    confirmLoading.value = true;

    if (isEdit.value) {
      // 编辑模式 - 调用更新API
      const params = [
        {
          name: formData.name,
          visibleScope: formData.visibleScope,
          tagId: formData.tagId
        }
      ];

      const response = await sensitiveApi.updateSensitiveDisease(params);

      if (response.code === 0) {
        ElMessage.success("编辑成功");
        dialogVisible.value = false;
        loadData(); // 重新加载数据
      } else {
        ElMessage.error(response.message || "编辑失败");
      }
    } else {
      // 添加模式 - 调用创建API
      const params = {
        name: formData.name,
        visibleScope: formData.visibleScope
      };

      const response = await sensitiveApi.createSensitiveDisease(params);

      if (response.code === 0) {
        ElMessage.success("添加成功");
        dialogVisible.value = false;
        loadData(); // 重新加载数据
      } else {
        ElMessage.error(response.message || "添加失败");
      }
    }
  } catch (error) {
    console.error(isEdit.value ? "编辑失败:" : "添加失败:", error);
    ElMessage.error(isEdit.value ? "编辑失败，请重试" : "添加失败，请重试");
  } finally {
    confirmLoading.value = false;
  }
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="scss" scoped>
.sensitive-disease-container {
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;
  .search-section {
    // padding: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 24px;

    .search-row {
      display: flex;
      gap: 16px;
      align-items: center;

      .search-input {
        width: 300px;
      }

      .category-select {
        width: 200px;
      }
    }
  }

  .tip-section {
    margin-bottom: 16px;
  }

  .table-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        margin: 0;
        color: #333;
        font-size: 18px;
        font-weight: 600;
      }
    }

    .disease-table {
      margin-bottom: 20px;
    }

    .pagination-section {
      display: flex;
      justify-content: center;
      padding-top: 20px;
    }
  }

  .save-section {
    text-align: center;

    .el-button {
      padding: 12px 40px;
      font-size: 16px;
    }
  }
}

// 对话框样式
:deep(.el-dialog) {
  .dialog-footer {
    text-align: right;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .sensitive-disease-container {
    padding: 10px;

    .search-section {
      .search-row {
        flex-direction: column;
        align-items: stretch;

        .search-input,
        .category-select {
          width: 100%;
        }
      }
    }

    .table-section {
      padding: 15px;

      .table-header {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
      }
    }
  }
}
</style>
